import React, { createContext, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { authAPI, tokenManager } from '../utils/api';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);
  const [isManualLogout, setIsManualLogout] = useState(false);
  const [tokenInfo, setTokenInfo] = useState(null);
  const navigate = useNavigate();

  // 更新令牌信息
  const updateTokenInfo = async () => {
    try {
      const info = await authAPI.getTokenInfo();
      setTokenInfo(info);
      return info;
    } catch (error) {
      console.error('获取令牌信息失败:', error);
      return null;
    }
  };

  // 检查并刷新令牌 - 使用TokenManager
  const checkAndRefreshToken = async () => {
    try {
      const result = await tokenManager.refreshTokens();
      console.log('令牌刷新成功');
      return true;
    } catch (error) {
      console.error('令牌刷新失败:', error);
      clearAuthData();
      return false;
    }
  };

  // 清除认证数据
  const clearAuthData = () => {
    tokenManager.clearTokens();
    localStorage.removeItem('token'); // 兼容旧版本
    setUser(null);
    setIsAuthenticated(false);
    setTokenInfo(null);
  };

  // 初始化：检查本地存储的token并验证
  useEffect(() => {
    const initAuth = async () => {
      // 兼容旧版本的token字段
      const oldToken = localStorage.getItem('token');
      const accessToken = tokenManager.getAccessToken();
      const refreshToken = tokenManager.getRefreshToken();

      // 如果有旧版本token，清除它
      if (oldToken && !accessToken) {
        localStorage.removeItem('token');
      }

      if (accessToken) {
        try {
          // 尝试获取用户信息
          const response = await authAPI.getCurrentUser();
          setUser(response);
          setIsAuthenticated(true);
          setIsManualLogout(false);
          
          // 获取令牌信息
          await updateTokenInfo();
        } catch (error) {
          console.error('Token验证失败:', error);
          
          // 如果访问令牌失效，尝试使用刷新令牌
          if (refreshToken) {
            const refreshed = await checkAndRefreshToken();
            if (refreshed) {
              // 刷新成功，重新获取用户信息
              try {
                const response = await authAPI.getCurrentUser();
                setUser(response);
                setIsAuthenticated(true);
                setIsManualLogout(false);
                await updateTokenInfo();
              } catch (retryError) {
                console.error('刷新后获取用户信息失败:', retryError);
                clearAuthData();
              }
            }
          } else {
            clearAuthData();
          }
        }
      }
      setLoading(false);
    };

    initAuth();
  }, []);

  // 定期检查令牌状态
  useEffect(() => {
    if (!isAuthenticated) return;

    const checkTokenStatus = async () => {
      const info = await updateTokenInfo();
      if (info && info.should_refresh && !info.is_expired) {
        console.log('令牌即将过期，自动刷新');
        await checkAndRefreshToken();
      }
    };

    // 每5分钟检查一次令牌状态
    const interval = setInterval(checkTokenStatus, 5 * 60 * 1000);

    return () => clearInterval(interval);
  }, [isAuthenticated]);

  // 登录
  const login = async (username, password) => {
    try {
      setLoading(true);
      const response = await authAPI.login(username, password);
      const { access_token, refresh_token } = response;
      
      // 使用TokenManager保存令牌
      tokenManager.setTokens(access_token, refresh_token);
      
      // 清除旧版本token
      localStorage.removeItem('token');

      // 获取用户信息
      const userResponse = await authAPI.getCurrentUser();
      setUser(userResponse);
      setIsAuthenticated(true);
      setIsManualLogout(false);
      
      // 获取令牌信息
      await updateTokenInfo();
      
      message.success('登录成功');
      return true;
    } catch (error) {
      console.error('登录失败:', error);
      message.error(error.response?.data?.detail || '登录失败，请检查用户名和密码');
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 登出
  const logout = async (logoutAllDevices = false) => {
    try {
      const refreshToken = tokenManager.getRefreshToken();
      await authAPI.logout(refreshToken);
      message.success('已成功登出');
    } catch (error) {
      console.error('登出请求失败:', error);
    } finally {
      // 清除本地存储和状态
      clearAuthData();
      setIsManualLogout(true);
      
      // 直接跳转到NewHome页面
      navigate('/new-home', { replace: true });
      
      // 延迟清除主动登出标记，确保跳转完成
      setTimeout(() => {
        setIsManualLogout(false);
      }, 100);
    }
  };

  // 手动刷新令牌 - 使用TokenManager
  const refreshToken = async () => {
    return await checkAndRefreshToken();
  };

  // 获取令牌剩余时间
  const getTokenRemainingTime = () => {
    if (!tokenInfo) return null;
    return {
      remainingSeconds: tokenInfo.remaining_seconds,
      shouldRefresh: tokenInfo.should_refresh,
      isExpired: tokenInfo.is_expired
    };
  };

  const value = {
    user,
    isAuthenticated,
    loading,
    login,
    logout,
    isManualLogout,
    tokenInfo,
    refreshToken,
    getTokenRemainingTime,
    updateTokenInfo
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// 自定义hook，方便组件使用认证上下文
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export default AuthContext;